package com.itheima.app.interceptor;


import cn.hutool.core.bean.BeanUtil;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

//token拦截器
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //0. 获取token
        String token = request.getHeader("Authorization");

        //1. 判断token是否为空,如果是空,返回401
        if (StringUtils.isEmpty(token)) {
            response.setStatus(401);
            return false;
        }

        //2. 判断token是否在有效期,如果失效,返回401
        Boolean hasKey = stringRedisTemplate.hasKey(ConstantUtil.USER_TOKEN + token);
        if (!hasKey) {
            response.setStatus(401);
            return false;
        }

        //3. 解析token
        try {
            Map map = JwtUtil.parseToken(token);//id  phone
            User user = BeanUtil.mapToBean(map, User.class, true);

            //成功
            // 1) 执行token续期
            stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, "1", Duration.ofDays(30));

            // 2) 将user放入ThreadLocal
            UserHolder.set(user);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            //失败,返回401
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
